import React, { useState, useEffect } from 'react';
import { List, Avatar, Space, message, Popconfirm } from 'antd';
import { MessageOutlined, LikeOutlined, EyeOutlined, HistoryOutlined, DeleteOutlined, QuestionCircleOutlined } from '@ant-design/icons';

import './styleBox/Messages.scss'

const IconText = ({ icon, text }) => (
  <Space>
    {React.createElement(icon)}
    {text}
  </Space>
);

export default () => {
  const [postList, setPostList] = useState([])

  // 先预设一个currentPostId 来装当前点击的帖子id
  let currentPostId = null;
  const deleteGood = (gid) => {
    currentPostId = gid
  }

  // 管理员点击“确定”后的行为
  function confirm(e) {
    console.log("confirm id=>", currentPostId);
    message.success('删除成功');

    const doDeletePost = async (currentPostId) => {
      // 声明新的 cloud 实例
      let c1 = new window.cloud.Cloud({
        // 必填，表示是未登录模式
        identityless: true,
        // 资源方 AppID 填我自己小程序的微信公众平台id
        resourceAppid: 'wxeedf95a9015b2b59',
        // 资源方环境 ID	填我自己的云开发的环境
        resourceEnv: 'caicren1-9ga67iu1c258fa35',
      })
      //初始化
      await c1.init()
      //初始化执行完再调用

      // 完成后正常使用资源方的已授权的云资源
      c1.callFunction({
        name: 'deletePost',    //调用的云函数名字
        data: {
          currentPostId: currentPostId + '',
        },
        success: res => {
          console.log("deletePost res", res);
          message.success('帖子删除成功')
          window.location.reload()
        },
        fail(err) {
          console.log("callFunction err=", err);
          message.error('帖子删除失败')
        }
      })
    }
    doDeletePost(currentPostId)
  }

  // 管理员点击“取消”后的行为
  function cancel(e) {
    message.error('取消删除');
  }

  const getData = async () => {
    // 声明新的 cloud 实例
    let c1 = new window.cloud.Cloud({
      // 必填，表示是未登录模式
      identityless: true,
      // 资源方 AppID 填自己的
      resourceAppid: 'wxeedf95a9015b2b59',
      // 资源方环境 ID	填自己的
      resourceEnv: 'caicren1-9ga67iu1c258fa35',
    })
    //初始化
    await c1.init()
    //初始化执行完再调用

    // 完成后正常使用资源方的已授权的云资源
    c1.callFunction({
      name: 'getPost',    //调用的云函数名字
      success: res => {
        let tempData = res.result.data
        // console.log("tempData", tempData);
        setPostList(() => tempData.map(item => ({ ...item, key: item._id })))
      },
      fail(err) {
        console.log("callFunction err=", err);
      }
    })
  }

  useEffect(
    async () => {
      getData()
    },
    []
  )

  return (
    <List
      itemLayout="vertical"
      size="large"
      pagination={{
        onChange: page => {
          console.log(page);
        },
        pageSize: 3,
      }}
      dataSource={postList}
      footer={
        <div>
          <b>* 管理员对用户发布的帖子有删除的权限</b> (管理员应根据事实来判断，而不是滥用权力)
        </div>
      }
      renderItem={item => (
        <List.Item
          key={item._id}
          actions={[
            <IconText icon={EyeOutlined} text={60 + Math.round(Math.random() * 767)} key="list-vertical-star-o" />,
            <IconText icon={LikeOutlined} text={item.hits} key="list-vertical-like-o" />,
            <IconText icon={MessageOutlined} text={Math.round(Math.random() * 6)} key="list-vertical-message" />,
            <IconText icon={HistoryOutlined} text={item.publishTime} key="list-vertical-publishTime" />,
            <Popconfirm
              onClick={e => deleteGood(e.target.children[0].innerText)}
              className='deleBox'
              title="你确定需要删除该帖子吗？"
              onConfirm={confirm}
              onCancel={cancel}
              icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
              okText="Yes"
              cancelText="No"
            >
              <text style={{ display: 'none' }}>{item._id}</text>
              <IconText icon={DeleteOutlined} text='' key="DeleteOutlined" />
              <text className='deletePost'>
                删除<b style={{ display: 'none' }}>{item._id}</b>
              </text>
            </Popconfirm>
          ]}
          extra={
            <>
              <img
                width={300}
                alt="logo"
                // src="https://gw.alipayobjects.com/zos/rmsportal/mqaQswcyDLcXyDKnZfES.png"
                src={item.wdfImgUrl}
                className= {item.imgOrVideo1 ? '':'hideBox'}
              />
              <video id='postVideo' className= {item.imgOrVideo2 ? '':'hideBox'} controls>
                <source src={item.wdfImgUrl} />
              </video>
            </>
          }
        >
          <List.Item.Meta
            avatar={<Avatar src={item.avatarUrl} />}
            title={<a href={item.href}>{item.nickName}</a>}
            description={item.title}
          />
          {item.postContent}
        </List.Item>
      )}
    />
  )
};